﻿/*******************************************************************************
 * Copyright @ 2017 YunSpace.Framework 版权所有
 * Author: GaoTang
 * Description: YunSpace 快速开发平台
 * Website：http://www.yunspace.com.cn
*********************************************************************************/
#region USING SYSTEM
using YunSpace.Core;
using YunSpace.Domain.Entity.MiniSite;
using YunSpace.Domain.IRepository.MiniSite;
using YunSpace.Repository.MiniSite;
using System.Collections.Generic;
using System.Linq;
using YunSpace.Data;
using YunSpace.Domain.ViewModel.MiniSite;
using System.Data.Common;
using MySql.Data.MySqlClient;
using YunSpace.Domain.Entity.SiteLibraryManage;
#endregion

namespace YunSpace.Application.MiniSite
{
    public class SiteActivityApp
    {
        private ISiteActivityRepository service = new SiteActivityRepository();

        public List<SiteActivityEntity> GetList(Pagination pagination, string queryJson)
        {
            var expression = ExtLinq.True<SiteActivityEntity>();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["keyword"].IsEmpty())
            {
                string keyword = queryParam["keyword"].ToString();
                expression = expression.And(t => t.F_Title.Contains(keyword));
            }
            if (!queryParam["F_Status"].IsEmpty())
            {
                int F_Status = int.Parse(queryParam["F_Status"].ToString());
                expression = expression.And(t => t.F_Status == F_Status);
            }
            return service.FindList(expression, pagination);
        }


        public List<ActivityActionModel> GetSiteActivitys(string lastId, int count) {
            using (var db = new RepositoryBase().BeginTrans()) {
                var result = new List<ActivityActionModel>();
                var strSql = @"select a.F_Id,a.F_Title,a.F_Subject,a.F_Content,a.F_SiteId,a.F_ActivityType,a.F_SpaceId,a.F_ConsumeType,a.F_Price,a.F_StartTime,a.F_EndTime from MiniSite_SiteActivity a 
                               where 1=1 {0}
                               order by a.F_StartTime desc LIMIT 0, {1};";
                if (lastId.IsNullOrEmpty())
                {
                    strSql = string.Format(strSql, "", count);
                    result = db.FindList<ActivityActionModel>(strSql);
                }
                else
                {
                    strSql = string.Format(strSql, "AND a.F_Id > @fId", count);
                    DbParameter[] parameter =
                    {
                        new MySqlParameter("@fId", lastId)
                    };
                    result = db.FindList<ActivityActionModel>(strSql, parameter);
                }
                db.Commit();
                return result;
            }
        }

        public int OperationLog(OperationLogEntity entity) {
            using (var db = new RepositoryBase()) {
                return db.Insert<OperationLogEntity>(entity);                
            }
        }

        public ActivityActionModel GetSiteActivityById(string activityId,string customerId) {
            using (var db = new RepositoryBase()) {
                var strSql = @"select a.F_Id,a.F_Title,a.F_Subject,a.F_Address,a.F_SiteId,a.F_ActivityType,a.F_SpaceId,a.F_Content,a.F_ConsumeType,a.F_Price,a.F_StartTime,a.F_EndTime
                               ,case when fa.F_CustomerId is null then 0 else 1 end  Isfavorite from MiniSite_SiteActivity a
                                left join (select distinct f_favoriteid,F_CustomerId from MiniSite_Favorite  where  F_Type=2  AND F_Status =1   {0}) fa on fa.f_favoriteid = a.F_Id  
                              where a.F_Id=@activityId";
                strSql = string.Format(strSql, customerId.IsNullOrEmpty()? " and F_CustomerId=''" : " and F_CustomerId=@customerId");
                DbParameter[] parameter =
                {
                    new MySqlParameter("@activityId", activityId),
                    new MySqlParameter("@customerId",customerId)
                };
                return db.FindList<ActivityActionModel>(strSql, parameter).FirstOrDefault();
            }
        }

        public List<ActivityPhotoActionModel> GetActivityByIdAllphoto(string activityId) {
            using (var db = new RepositoryBase()) {
                var strSql = @"select a.f_id id,a.photoable_id,a.photoable_type,a.name,a.is_cover,a.path from SL_Photos a where a.photoable_id=@activityId";
                // and a.photoable_type='MiniSite_SiteActivity'

                DbParameter[] parameter =
                {
                    new MySqlParameter("@activityId", activityId)
                };
                return db.FindList<ActivityPhotoActionModel>(strSql, parameter);
            }
        }

        public SiteItemActionModel GetSiteItemById(string siteFId) {


            using (var db = new RepositoryBase()) {
                var strSql = @"select a.F_Id,a.title,a.brand_story,a.address,a.x_coordinates,a.y_conrdinates,c.inner_price,c.market_price from SL_Site a
                               inner join (select max(a.F_Id) F_Id,max(a.inner_price) inner_price,max(a.market_price) market_price,a.F_SiteId from SL_Space a group by a.F_SiteId) c on a.F_Id=c.F_SiteId
                              where a.F_Category=1 and a.F_Id=@siteFId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@siteFId", siteFId)
                };
                return db.FindList<SiteItemActionModel>(strSql, parameter).FirstOrDefault();
            }
        }

        public List<SiteItemPhotoActionModel> GetSiteByIdAllphoto(string siteFId) {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.f_id id,a.photoable_id,a.photoable_type,a.name,a.is_cover,a.path from SL_Photos a where 
                                 a.photoable_id=@siteFId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@siteFId", siteFId)
                };
                return db.FindList<SiteItemPhotoActionModel>(strSql, parameter);
            }
        }

        public int InsertActivity(SiteActivityEntity model,List<string> photos) {
            using (var db = new RepositoryBase().BeginTrans()) {
                model.Create();
                model.F_ActivityType = 1;
                if (photos.Any())
                {                   
                    for (int i = 0; i < photos.Count; i++) {
                        var pp = new PhotosEntity
                        {
                            photoable_id = model.F_Id,
                            photoable_type = "MiniSite_SiteActivity",
                            name = photos[i].Substring(photos[i].LastIndexOf('/') + 1),
                            path = photos[i],
                            is_cover = i == 0 ? true : false
                        };
                        pp.Create();
                        db.Insert<PhotosEntity>(pp);
                    }
                }                
                var result= db.Insert<SiteActivityEntity>(model);
                db.Commit();
                return result;
            }                
        }

        public SiteActivityEntity GetActivityById(string id)
        {            
            return service.FindEntity(id);
        }

        public SiteActivityEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }
        public void UpStateForm(SiteActivityEntity siteactivityEntity, string keyValue)
        {
            siteactivityEntity.Modify(keyValue);
            service.Update(siteactivityEntity);
        }
        public void SubmitForm(SiteActivityEntity siteactivityEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                siteactivityEntity.Modify(keyValue);
                service.Update(siteactivityEntity);
            }
            else
            {
                siteactivityEntity.Create();
                // 状态 0.活动初始; 1.未开始; 2.进行中; 3.已结束; 4.待评价; 5.已完结
                siteactivityEntity.F_Status = 0;
                service.Insert(siteactivityEntity);
            }
        }

        #region MiniActivities

        public List<ActivityEntityActionModel> GetActivities(string customerId, string lastId, int type,int count)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = "";
                if (type == 2)
                {
                     strSql = @"select a.F_Id,a.F_Title,a.F_Subject,a.F_Address,a.F_Content,a.F_Price,a.F_ActivityType,a.F_CommunityObjectType,a.F_ConsumeType,a.F_TripType,a.F_StartTime,a.F_EndTime,
                               a.F_DesignatedCustomer,b.path photoUrl  from MiniSite_SiteActivity a
                                left join SL_Photos b on a.F_Id=b.photoable_id and b.is_cover=1 
                                WHERE  a.F_CustomerId  IS NOT  NULL {1}  {0}  
                                  ORDER BY a.F_CreatorTime DESC
                                  LIMIT 0, @count";
                    strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : "AND a.F_CreatorTime <(select F_CreatorTime from MiniSite_SiteActivity where f_id= @fId)", customerId.IsNullOrEmpty() ? "AND a.F_CustomerId=''" : "AND a.F_CustomerId=@customerId");
                }
                else
                {
                    strSql = @"select a.F_Id,a.F_Title,a.F_Subject,a.F_Address,a.F_Content,a.F_Price,a.F_ActivityType,a.F_CommunityObjectType,a.F_ConsumeType,a.F_TripType,a.F_StartTime,a.F_EndTime,
                               a.F_DesignatedCustomer,b.path photoUrl,case when fa.F_CustomerId is null then 0 else 1 end isfavorite from MiniSite_SiteActivity a
                                left join SL_Photos b on a.F_Id=b.photoable_id and b.is_cover=1
                                left join (select distinct f_favoriteid,F_CustomerId from MiniSite_Favorite where  F_Status=1 AND F_Type =2 {1}) fa on a.F_Id=fa.F_FavoriteId 
                                  WHERE a.F_IsPublic=1 {0}
                                  ORDER BY a.F_CreatorTime DESC
                                  LIMIT 0, @count";
                    strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : "AND a.F_CreatorTime <(select F_CreatorTime from MiniSite_SiteActivity where f_id= @fId)", customerId.IsNullOrEmpty() ? "" : "and F_CustomerId=@customerId");

                }

                DbParameter[] parameter =
                {
                    new MySqlParameter("@fId", lastId),
                    new MySqlParameter("@customerId", customerId),
                    new MySqlParameter("@count", count)
                };
                return db.FindList<ActivityEntityActionModel>(strSql, parameter);
            }
        }

        public List<SiteActivityEntity> GetMyActivities(string customerId, string lastId, int count)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"SELECT * FROM MiniSite_SiteActivity msa
                                  WHERE msa.F_CustomerId = @customerId {0}
                                  ORDER BY msa.F_CreatorTime DESC
                                  LIMIT 0, @count";
                if (string.IsNullOrEmpty(lastId))
                    strSql = string.Format(strSql, "AND msa.F_Id > @fId");


                DbParameter[] parameter =
                {
                    new MySqlParameter("@customerId", customerId),
                    new MySqlParameter("@fId", lastId),
                    new MySqlParameter("@count", count)
                };
                return db.FindList<SiteActivityEntity>(strSql, parameter);
            }
        }

        #endregion
    }
}

